//
//  ToolManager.m
//  yuntangyi
//
//  Created by yuntangyi on 16/8/29.
//  Copyright © 2016年 yuntangyi. All rights reserved.
//

#import "ToolManager.h"

#import <sys/utsname.h>
#import<CommonCrypto/CommonDigest.h>
#import "LoginViewController.h"

// 最大存储的搜索历史 条数
#define MAX_COUNT 5

@implementation ToolManager


static ToolManager *manager;
//单例的创建
+(instancetype)sharedManager{
    if (!manager) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[ToolManager alloc]init];
        });
    }
    return manager;
}

//获得当前的时间戳
+ (NSString *)getCurrentTimeStamp {
    NSDate *date = [NSDate date];
    NSTimeInterval timeStamp = [date timeIntervalSince1970];
    return [NSString stringWithFormat:@"%d",(int)timeStamp + arc4random() % 1000];
    
}
//加密
+ (NSString *)secureMD5WithString:(NSString *)string {
    //加盐
    NSString *salt = @"uGUg*YIU98U*YIsdfas233245$#$%##657^&(&dugHY78^%7657^^98)u((*y9*9Y*&yGhJsdfasd23534tergkdfm1$%%fgcIY(*yt7^R&^8Y(*(HIHG8yyT&^t&^*98Y8546556&**^%^#%#@YTfgF6te%^$rew4w$#3@W7uY*";
    NSMutableString *str = [NSMutableString stringWithFormat:@"%@",string];
    [str appendString:salt];
    
    const char *cStr = [str UTF8String];
    unsigned long length = strlen(cStr);
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)length, result);
    
    NSMutableString *secureString = [NSMutableString string];
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [secureString appendFormat:@"%02X", result[i]];
    }
    
    return secureString;
}

//获得版本号
+ (NSString *)getVersion {
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    NSString *currentVersion = [infoDic objectForKey:@"CFBundleShortVersionString"];
    return currentVersion;
}
//获取当前时间str
- (NSString *)getCurrentTimeStrWithFormatterString:(NSString *)formatterString{
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:formatterString];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}


//判断手机型号
- (NSString *)iphoneType {
    
//    需要导入头文件：#import <sys/utsname.h>
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone 7";
    
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone 7 Plus";
    
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPod Touch 1G";
    
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPod Touch 2G";
    
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPod Touch 3G";
    
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPod Touch 4G";
    
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPod Touch 5G";
    
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad 1G";
    
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad 2";
    
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad Mini 1G";
    
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad 3";
    
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad 4";
    
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPad Air";
    
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPad Mini 2G";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhone Simulator";
    
    if ([platform isEqualToString:@"x86_64"])    return @"iPhone Simulator";
    
    return platform;
}


/**
 *  计算一个view相对于屏幕(去除顶部statusbar的20像素)的坐标
 *  iOS7下UIViewController.view是默认全屏的，要把这20像素考虑进去
 */
+ (CGRect)relativeFrameForScreenWithView:(UIView *)v
{
    BOOL iOS7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7;
    
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;
    if (!iOS7) {
        screenHeight -= 20;
    }
    UIView *view = v;
    CGFloat x = .0;
    CGFloat y = .0;
    while (view.frame.size.width != 320 || view.frame.size.height != screenHeight) {
        x += view.frame.origin.x;
        y += view.frame.origin.y;
        view = view.superview;
        if ([view isKindOfClass:[UIScrollView class]]) {
            x -= ((UIScrollView *) view).contentOffset.x;
            y -= ((UIScrollView *) view).contentOffset.y;
        }
    }
    return CGRectMake(x, y, v.frame.size.width, v.frame.size.height);
}

//label的闪烁
- (void)shimmerHeaderTitle:(UILabel *)title {
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.75f delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
        title.transform = CGAffineTransformMakeScale(0.98, 0.98);
        title.alpha = 0.3;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.75f delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            title.alpha = 1.0;
            title.transform = CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
            [weakSelf shimmerHeaderTitle:title];
        }];
    }];
}

//判断登录状态
-(BOOL)checkLoginStateAtVC:(BaseVC *)superVC{
    if (!kStringIsEmpty(k_user_token)) {//已登录
        return YES;
    }else{
        [XHToast showBottomWithText:@"您还没有登录，或者您的账号已在别的地方登录"];
        //跳转到登录界面
        LoginViewController *login_VC = [[LoginViewController alloc]init];
        login_VC.isFirstClass = NO;
        login_VC.isPresentLoginVC = YES;
        login_VC.currentReturnType = DismissType;
        login_VC.presentSourceVC = superVC;
        login_VC.sourceVC = NSStringFromClass([superVC class]);
        BaseNavigationC *navi = [[BaseNavigationC alloc]initWithRootViewController:login_VC];
        [superVC presentViewController:navi animated:YES completion:nil];
        return NO;
    }
}
//退出登录
-(void)logoutACTIONFromSuperVC:(BaseVC *)superVC{
    
    [[EMClient sharedClient] logout:YES completion:^(EMError *aError) {
        
        //将cookie 清除
        [kUserDefaults removeObjectForKey:@"user_token"];
        [kUserDefaults synchronize];
        //跳转到登录界面
        LoginViewController *login_VC = [[LoginViewController alloc]init];
        login_VC.isFirstClass = NO;
        login_VC.isPresentLoginVC = YES;
        login_VC.currentReturnType = DismissType;
        login_VC.presentSourceVC = superVC;
        login_VC.sourceVC = NSStringFromClass([superVC class]);
        BaseNavigationC *navi = [[BaseNavigationC alloc]initWithRootViewController:login_VC];
        [superVC presentViewController:navi animated:YES completion:nil];
    }];
    
    
}

//获取Window当前显示的ViewController
- (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}


#pragma mark -缓存
#pragma mark - 获取path路径下文件夹大小
+ (NSString *)getCacheSizeWithFilePath:(NSString *)path{
    
    // 获取“path”文件夹下的所有文件
    NSArray *subPathArr = [[NSFileManager defaultManager] subpathsAtPath:path];
    NSString *filePath  = nil;
    NSInteger totleSize = 0;
    for (NSString *subPath in subPathArr){
        // 1. 拼接每一个文件的全路径
        filePath =[path stringByAppendingPathComponent:subPath];
        // 2. 是否是文件夹，默认不是
        BOOL isDirectory = NO;
        // 3. 判断文件是否存在
        BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isDirectory];
        // 4. 以上判断目的是忽略不需要计算的文件
        if (!isExist || isDirectory || [filePath containsString:@".DS"]){
            // 过滤: 1. 文件夹不存在  2. 过滤文件夹  3. 隐藏文件
            continue;
        }
        // 5. 指定路径，获取这个路径的属性
        NSDictionary *dict = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        /**
         attributesOfItemAtPath: 文件夹路径
         该方法只能获取文件的属性, 无法获取文件夹属性, 所以也是需要遍历文件夹的每一个文件的原因
         */
        // 6. 获取每一个文件的大小
        NSInteger size = [dict[@"NSFileSize"] integerValue];
        // 7. 计算总大小
        totleSize += size;
    }
    //8. 将文件夹大小转换为 M/KB/B
    NSString *totleStr = nil;
    if (totleSize > 1000 * 1000){
        totleStr = [NSString stringWithFormat:@"%.2fM",totleSize / 1000.00f /1000.00f];
    }else if (totleSize > 1000){
        totleStr = [NSString stringWithFormat:@"%.2fKB",totleSize / 1000.00f ];
    }else{
        totleStr = [NSString stringWithFormat:@"%.2fB",totleSize / 1.00f];
    }
    return totleStr;
}


#pragma mark - 清除path文件夹下缓存大小
+ (BOOL)clearCacheWithFilePath:(NSString *)path{
    //拿到path路径的下一级目录的子文件夹
    NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    NSString *filePath = nil;
    NSError *error = nil;
    for (NSString *subPath in subPathArr)
    {
        filePath = [path stringByAppendingPathComponent:subPath];
        //删除子文件夹
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (error) {
            return NO;
        }
    }
    return YES;
}


#pragma mark -日期相关
// 获取当月的天数
- (NSInteger)getNumberOfDaysInMonth
{
    NSCalendar * calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian]; // 指定日历的算法 NSGregorianCalendar - ios 8
    NSDate * currentDate = [NSDate date];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay  //NSDayCalendarUnit - ios 8
                                   inUnit: NSCalendarUnitMonth //NSMonthCalendarUnit - ios 8
                                  forDate:currentDate];
    return range.length;
}
//获取过去一周时间 数组
- (NSMutableArray *)getPastWeekDateStringArr{
    NSMutableArray *eightArr = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < 7; i ++) {
        //从现在开始的24小时
        NSTimeInterval secondsPerDay = -i * 24*60*60;
        NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"M月d日"];
        NSString *dateStr = [dateFormatter stringFromDate:curDate];//几月几号
        //        NSString *dateStr = @"5月31日";
        NSDateFormatter *weekFormatter = [[NSDateFormatter alloc] init];
        [weekFormatter setDateFormat:@"EEEE"];//星期几 @"HH:mm 'on' EEEE MMMM d"];
        NSString *weekStr = [weekFormatter stringFromDate:curDate];
        //组合时间
//        NSString *strTime = [NSString stringWithFormat:@"%@(%@)",dateStr,weekStr];
//        [eightArr addObject:strTime];

        [eightArr addObject:dateStr];
    }
    return eightArr;
}
//获取未来一周时间 数组
- (NSMutableArray *)getFeatureWeekDateStringArr{
    NSMutableArray *eightArr = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < 7; i ++) {
        //从现在开始的24小时
        NSTimeInterval secondsPerDay = i * 24*60*60;
        NSDate *curDate = [NSDate dateWithTimeIntervalSinceNow:secondsPerDay];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"M月d日"];
        NSString *dateStr = [dateFormatter stringFromDate:curDate];//几月几号
        //        NSString *dateStr = @"5月31日";
        NSDateFormatter *weekFormatter = [[NSDateFormatter alloc] init];
        [weekFormatter setDateFormat:@"EEEE"];//星期几 @"HH:mm 'on' EEEE MMMM d"];
        NSString *weekStr = [weekFormatter stringFromDate:curDate];
        //组合时间
        //        NSString *strTime = [NSString stringWithFormat:@"%@(%@)",dateStr,weekStr];
        //        [eightArr addObject:strTime];
        
        [eightArr addObject:dateStr];
    }
    return eightArr;
}


#pragma mark -搜索关键字 操作
/**
 *  关键词插入数据库
 *
 *  @param keyword 关键词
 */
//- (NSMutableArray *)insterDBData:(NSString *)keyword{
//    //搜索历史插入数据库
//    //先删除数据库中相同的数据
//    [self removeSameData:keyword];
//    //再插入数据库
//    [self moreThan20Data:keyword];
//    // 读取数据库里面的数据
//    NSMutableArray *arr = [[SearchDBManage shareSearchDBManage] selectAllSearchModel];
//    return arr;
//}
/**
 *  获取当前时间
 *
 *  @return 当前时间
 */
- (NSString *)getCurrentTime{
    NSDate *  senddate=[NSDate date];
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"YYYY年MM月dd日HH:mm:ss"];
    NSString *  locationString=[dateformatter stringFromDate:senddate];
    return locationString;
}

/**
 *  去除数据库中已有的相同的关键词
 *
 *  @param keyword 关键词
 */
//- (void)removeSameData:(NSString *)keyword{
//    NSMutableArray *array = [[SearchDBManage shareSearchDBManage] selectAllSearchModel];
//    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        SearchModel *model = (SearchModel *)obj;
//        if ([model.keyWord isEqualToString:keyword]) {
//            [[SearchDBManage shareSearchDBManage] deleteSearchModelByKeyword:keyword];
//        }
//    }];
//}

/**
 *  数组左移
 *
 *  @param array   需要左移的数组
 *  @param keyword 搜索关键字
 *
 *  @return 返回新的数组
 */
//- (NSMutableArray *)moveArrayToLeft:(NSMutableArray *)array keyword:(NSString *)keyword{
//    [array addObject:[SearchModel creatSearchModel:keyword currentTime:[self getCurrentTime]]];
//    [array removeObjectAtIndex:0];
//    return array;
//}
/**
 *  数组逆序
 *
 *  @param array 需要逆序的数组
 *
 *  @return 逆序后的输出
 */
- (NSMutableArray *)exchangeArray:(NSMutableArray *)array{
    NSInteger num = array.count;
    NSMutableArray *temp = [[NSMutableArray alloc] init];
    for (NSInteger i = num - 1; i >= 0; i --) {
        [temp addObject:[array objectAtIndex:i]];
        
    }
    return temp;
}
/**
 *  多余20条数据就把第0条去除
 *
 *  @param keyword 插入数据库的模型需要的关键字
 */
//- (void)moreThan20Data:(NSString *)keyword{
//    // 读取数据库里面的数据
//    NSMutableArray *array = [[SearchDBManage shareSearchDBManage] selectAllSearchModel];
//
//    if (array.count > MAX_COUNT - 1) {
//        NSMutableArray *temp = [self moveArrayToLeft:array keyword:keyword]; // 数组左移
//        [[SearchDBManage shareSearchDBManage] deleteAllSearchModel]; //清空数据库
////        [self.dataArray removeAllObjects];
////        [self.tableView reloadData];
//        [temp enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//            SearchModel *model = (SearchModel *)obj; // 取出 数组里面的搜索模型
//            [[SearchDBManage shareSearchDBManage] insterSearchModel:model]; // 插入数据库
//        }];
//    }
//    else if (array.count <= MAX_COUNT - 1){ // 小于等于19 就把第20条插入数据库
//        [[SearchDBManage shareSearchDBManage] insterSearchModel:[SearchModel creatSearchModel:keyword currentTime:[self getCurrentTime]]];
//    }
//}



#pragma mark -获取图片加载路径
-(NSString *)getNetImageUrlWith:(NSString *)path{
    if (![path containsString:@"http"]) {
        return [NSString stringWithFormat:@"%@%@",kBaseImageUrl,path];
    }else{
        return path;
    }
}





@end
